<?php

namespace app\newmerchant\controller;

use app\merchant\model\system\SystemAdmin;
use app\merchant\model\system\SystemMenus;
use app\merchant\model\system\SystemRole;
use app\models\user\UserToken;
use think\facade\Route as Url;
use Firebase\JWT\JWT;
use think\facade\Config;
use think\facade\Db;
/**
 * 基类 所有控制器继承的类
 * Class AuthController
 * @package app\merchant\controller
 */
class AuthController extends SystemBasic
{
    /**
     * 当前登陆管理员信息
     * @var
     */
    protected $adminInfo;

    /**
     * 当前登陆管理员ID
     * @var
     */
    protected $adminId;

    /**
     * 当前管理员权限
     * @var array
     */
    protected $auth = [];

    protected $skipLogController = ['index', 'common'];

    protected function initialize()
    {
        parent::initialize();
        $account=$this->request->header('account');
        $token=$this->request->header('token');

        $re=Db::name('merchant_admin')->where(['account'=>$account,'token'=>$token])->find();
        if(!$re)return app('json')->fail('用户不存在');
        if(!$re['status']) return app('json')->fail('用户被禁用');

        $this->adminInfo = $re;
        $this->adminId = $re['id'];
        $buy_url = "http://web.sikeduo.net/index/index?mer_id=".$this->adminId;
//        $this->assign('buy_url', $buy_url);
//        $this->auth = SystemAdmin::activeAdminAuthOrFail();
//        $version = $adminInfo['version'];
//        $this->assign('version', $version);
//        $this->assign('_admin', $this->adminInfo);
//        $type = 'system';
//        event('AdminVisit', [$this->adminInfo, $type]);
    }


    protected function checkAuth($action = null, $controller = null, $module = null, array $route = [])
    {
        static $allAuth = null;
        if ($allAuth === null) $allAuth = SystemRole::getAllAuth();
        if ($module === null) $module = app('http')->getName();
        if ($controller === null) $controller = $this->request->controller();
        if ($action === null) $action = $this->request->action();
        if (!count($route)) $route = $this->request->route();
        if (in_array(strtolower($controller), $this->skipLogController, true)) return true;
        $nowAuthName = SystemMenus::getAuthName($action, $controller, $module, $route);
        $baseNowAuthName = SystemMenus::getAuthName($action, $controller, $module, []);
        if ((in_array($nowAuthName, $allAuth) && !in_array($nowAuthName, $this->auth)) || (in_array($baseNowAuthName, $allAuth) && !in_array($baseNowAuthName, $this->auth)))
            exit($this->failed('没有权限访问!'));
        return true;
    }


    /**
     * 获得当前用户最新信息
     * @return SystemAdmin
     */
    protected function getActiveAdminInfo()
    {
        $adminId = $this->adminId;
        $adminInfo = SystemAdmin::getValidAdminInfoOrFail($adminId);
        if (!$adminInfo) $this->failed(SystemAdmin::getErrorInfo('请登陆!'));
        $this->adminInfo = $adminInfo;
        SystemAdmin::setLoginInfo($adminInfo);
        return $adminInfo;
    }

    //TODO  小松新增方法start
    public static function getToken($userInfo){
        $key = "huang";  //这里是自定义的一个随机字串，应该写在config文件中的，解密时也会用，相当    于加密中常用的 盐  salt
        $token = [
            "iss"=>"",  //签发者 可以为空
            "aud"=>"", //面象的用户，可以为空
            "iat" => time(), //签发时间
            "nbf" => time()+100, //在什么时候jwt开始生效  （这里表示生成100秒后才生效）
            "exp" => time()+7200, //token 过期时间
//            'jti' => '',
            "userInfo" => $userInfo //记录的userid的信息，这里是自已添加上去的，如果有其它信息，可以再添加数组的键值对
        ];

        $jwt = JWT::encode($token,$key,"HS256"); //根据参数生成了 token
        UserToken::create([
            'uid' => $userInfo->id,
            'token' => $jwt,
            'expires_time' => date('Y-m-d H:i:s', $token['exp']),
            'type' => 2
        ]);
        return [
            "token"=>$jwt
        ];
    }

    public static function check($jwt){
        $key = "huang";
        JWT::$leeway+=60;
        $info = JWT::decode($jwt,$key,["HS256"]); //解密jwt
        return ((array)$info)['userInfo'];
        return $info;
    }

    //TODO  小松新增方法end
}